package com.ruoyi.web.controller.tool;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.Set;

public class SHA256Utils {

    public static final String url = "http://devel.sunhj.cn:7014/open/api/grid";
    public static final String appId = "c7aec2a8031b4fae95f9f6de43a1774f";
    public static final String app_secret = "7287d527a3aa4464af26ec49f4a35fc4";
    /**
     * 利用java原生的类实现SHA256加密
     *
     */
    public static String getSHA256(String str) {
        MessageDigest messageDigest;
        String encodeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes("UTF-8"));
            encodeStr = byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encodeStr;
    }

    /**
     * 将byte转为16进制
     *
     * @param bytes
     * @return
     */
    private static String byte2Hex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        String temp = null;
        for (byte aByte : bytes) {
            temp = Integer.toHexString(aByte & 0xFF);
            if (temp.length() == 1) {
                // 1得到一位的进行补0操作
                sb.append("0");
            }
            sb.append(temp);
        }
        return sb.toString();
    }





    /**
     * 生成签名（SHA256）
     *
     * @param data   待签名数据
     * @param appKey API密钥
     * @return 签名
     */
    public static String generateSignature(final Map<String, String> data, String appKey) {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if ("sign".equals(k)) {
                continue;
            }
            if (data.get(k) instanceof String) {
                // 参数值为空，则不参与签名
                if (data.get(k).trim().length() > 0) {
                    sb.append(k).append("=").append(data.get(k).trim()).append("&");
                }
            }


        }
        sb.append("key=").append(appKey);
        return SHA256Utils.getSHA256(sb.toString());
    }

    public static String getAlertQueryResult(){
        String method = "Alert.Query";
        String version = "1.0";
        String format = "json";
        String timestamp = createTime();
        String nonce = randomSixNumber();
        JSONObject jsonObject = JSONUtil.createObj()
//                .set("alertId", UUID.randomUUID().toString())
                .set("hi", "test from bo liu")
                .set("pageIndex", 1)
                .set("pageSize", 50);
        String data = jsonObject.toString();
        String sign = encryptSign(appId,app_secret,timestamp,nonce,data,method,version,format);
        JSONObject json = JSONUtil.createObj()
                .set("appId", appId)
                .set("app_secret", app_secret)
                .set("method", method)
                .set("version", version)
                .set("format", format)
                .set("timestamp", timestamp)
                .set("nonce", nonce)
                .set("sign", sign)
                .set("data", data);
        String s = HttpUtil.post(url,json);
        return s;
    }
    public static String inspectionQueryResult(){
        String method = "Inspection.Query";
        String version = "1.0";
        String format = "json";
        String timestamp = createTime();
        String nonce = randomSixNumber();
        JSONObject jsonObject = JSONUtil.createObj()
//                .set("alertId", UUID.randomUUID().toString())
                .set("pageIndex", 1)
                .set("pageSize", 50);
        String data = jsonObject.toString();
        String sign = encryptSign(appId,app_secret,timestamp,nonce,data,method,version,format);
        JSONObject json = JSONUtil.createObj()
                .set("appId", appId)
                .set("app_secret", app_secret)
                .set("method", method)
                .set("version", version)
                .set("format", format)
                .set("timestamp", timestamp)
                .set("nonce", nonce)
                .set("sign", sign)
                .set("data", data);
        String s = HttpUtil.post(url,json);
        return s;
    }

    public static String getAlertUploadResult(){
        String method = "Alert.Upload";
        String version = "1.0";
        String format = "json";
        String timestamp = createTime();
        String nonce = randomSixNumber();
        String data = "[{\"alertId\":\"ff8080817f1b555c017f25e9d1c6001a\",\"inspector\":\"liuTest\",\"inspectionTime\":\"2022-05-11 12:32:28\",\"content\":\"已进行协商解决\",\"files\":[{\"fileName\":\"巡查照片\",\"filePath\":\"http://110.42.216.252:9000/esfiles/9.jpg\"}]}]";

        String sign = encryptSign(appId,app_secret,timestamp,nonce,data,method,version,format);
        JSONObject json = JSONUtil.createObj()
                .set("appId", appId)
                .set("app_secret", app_secret)
                .set("method", method)
                .set("version", version)
                .set("format", format)
                .set("timestamp", timestamp)
                .set("nonce", nonce)
                .set("sign", sign)
                .set("data", data);
        return HttpUtil.post(url,json);
    }

    public static String InspectionUploadResult(){
        String method = "Inspection.Upload";
        String version = "1.0";
        String format = "json";
        String timestamp = createTime();
        String nonce = randomSixNumber();
        String data = "[{\n" +
                "  \"taskId\": \"402889a680a6e7370180b74b86515b08\",\n" +
                "  \"inspector\": \"0512test\",\n" +
                "  \"actualTime\": \"2022-05-12 16:22:45\",\n" +
                "  \"taskDetails\": [{\n" +
                "    \"taskDetailId\": \"402889a680a6e7370180a6f131800001\",\n" +
                "    \"content\": \"已进行协商解决完成\",\n" +
                "    \"files\": [{\n" +
                "        \"fileName\": \"巡查拍照图片1\",\n" +
                "        \"filePath\": \"http://110.42.216.252:9000/esfiles/6.jpg\"\n" +
                "      }\n" +
                "    ]\n" +
                "  },\n" +
                "  {\n" +
                "    \"taskDetailId\": \"402889a680a6e7370180a6f1328e0002\",\n" +
                "    \"content\": \"已进行协商解决完成\",\n" +
                "    \"files\": [{\n" +
                "        \"fileName\": \"巡查拍照图片2\",\n" +
                "        \"filePath\": \"http://110.42.216.252:9000/esfiles/8.jpg\"\n" +
                "      }\n" +
                "    ]\n" +
                "  },\n" +
                "  {\n" +
                "    \"taskDetailId\": \"402889a680a6e7370180a6f1328f0003\",\n" +
                "    \"content\": \"已进行协商解决完成\",\n" +
                "    \"files\": [{\n" +
                "        \"fileName\": \"巡查拍照图片3\",\n" +
                "        \"filePath\": \"http://110.42.216.252:9000/esfiles/9.jpg\"\n" +
                "      }\n" +
                "    ]\n" +
                "  }]\n" +
                "}]";
        String sign = encryptSign(appId,app_secret,timestamp,nonce,data,method,version,format);
        JSONObject json = JSONUtil.createObj()
                .set("appId", appId)
                .set("app_secret", app_secret)
                .set("method", method)
                .set("version", version)
                .set("format", format)
                .set("timestamp", timestamp)
                .set("nonce", nonce)
                .set("sign", sign)
                .set("data", data);
        return HttpUtil.post(url,json);
    }


    public static String encryptSign(String appId,String secret,String timestamp,String random,
                                     String data,String method,String version,String format) {
        StringBuffer str = new StringBuffer();
        str.append("appid=").append(appId)
                .append("&data=").append(data)
                .append("&format=").append(format)
                .append("&method=").append(method)
                .append("&nonce=").append(random)
                .append("&timestamp=").append(timestamp)
                .append("&version=").append(version);
        String sign = str.append("&appsecret=").append(secret).toString().toLowerCase();
        sign = SHA256Utils.getSHA256(sign);
        return sign;
    }

    public static String randomSixNumber() {
        return String.valueOf(RandomUtil.randomInt(100000, 999999));
    }

    public static String createTime() {
        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMddHHmmss");
        return ft.format(new Date());
    }

}
